package de.se.ludoapp.activity.task;

import android.content.Intent;
import android.os.AsyncTask;
import android.widget.Toast;
import de.se.ludoapp.LudoApplication;
import de.se.ludoapp.activity.GameActivity;
import de.se.ludoapp.activity.Select_menuActivity;
import de.se.ludoapp.response.ReturncodeResponse;

/**
 * Task to leave a running game.
 * 
 * @author Marlen Rotert
 * 
 */
public class LeaveRunningGameTask extends AsyncTask<String, Integer, String> {

	private LudoApplication ludoApp;
	private GameActivity context;
	private boolean isOk;

	public LeaveRunningGameTask(LudoApplication ludoApp, GameActivity context) {
		super();
		this.ludoApp = ludoApp;
		this.context = context;
		isOk = false;
	}

	/**
	 * sent request for game to server.<br>
	 * This method is executed in a concurrent thread (asynchronous). Therefore
	 * you mustn't accessed on view elements!
	 */
	@Override
	protected String doInBackground(String... params) {
		/* Execute leave Game */
		ReturncodeResponse response = ludoApp.getLudoStub().leaveRunningGame(
				ludoApp.getlogedinUser().getSessionId(),
				ludoApp.getCurrentGame().getGameId());
		if (response.getReturnCode() == 0) {
			this.isOk = true;
		}
		return response.getMsg();
	}

	/**
	 * Adapt Activity, when the request is sent. And ask for delays whether
	 * request is accepted. <br>
	 * This method is invoked when the OpenGameTask is executed. You are only
	 * allowed here to access on view Elements (TextView and Buttons)!
	 */
	@Override
	protected void onPostExecute(String result) {
		Toast.makeText(context, result, Toast.LENGTH_LONG).show();
		if (this.isOk == true) {
			Intent intentGame = new Intent(context, Select_menuActivity.class);
			context.startActivity(intentGame);
			context.finish();
		}

	}
}
